from datetime import datetime
from urllib.parse import quote

from lxml import etree


# 封装xpath提取
def parse_text(response, xpath):
    result_text = response.text
    tree = etree.HTML(result_text)
    result = tree.xpath(xpath)
    if any(result):
        return result[0]


# 根据参数名构建post参数
def build_poster(value, func_name):
    var = {
        "add_action": dict(
            WP_NAME=value.get("wpName", ""),
            WP_CODE=value.get("wpCode", ""),
            WP_PACKAGE=format_poster_value(value.get("wpPackage", "")),
            DEAL_FIELDS=value.get("dealFields", ""),
            DATE_MA_BEGIN=format_poster_date(value.get("dateMaBegin", "")),
            DATE_MA_END=format_poster_date(value.get("dateMaEnd", "")),
            DATE_STAT_BEGIN=format_poster_date(value.get("dateStatBegin", "")),
            DATE_STAT_END=format_poster_date(value.get("dateStatEnd", "")),
        ),
        "add_sales_rmd": dict(
            SALES_RMD=value.get("salesRmd", ""),
            JUDGE_ORDER=value.get("judgeOrder", ""),
            JUDGE_TYPE=format_poster_value(value.get("judgeType", "")),
            IMPORTANCE=format_poster_value(value.get("importance", "")),
            SUCCESS_SOURCE_CODE=value.get("successSourceCode", ""),
            FALSE_SOURCE_CODE=value.get("falseSourceCode", "")
        ),
        "wp_params_save": dict(
            PARAM_NAMES=build_wp_params(value.get("params", ""))[0],
            PARAM_SOURCES=build_wp_params(value.get("params", ""))[1]
        ),
        "wp_batch_save": dict(
            COMMIT_TYPE=format_poster_value("提交并导入号码清单")
            if any(value.get("path", "")) else format_poster_value("提交"),
            # COMMIT_TYPE="SI",
            AUTO_WP=format_poster_value(value.get("wp", "")),
            AUTO_WP_TYPE=",".join(
                [format_poster_value(x) for x in
                 eval((lambda x: "[]" if not x or not any(x) else x)(value.get("autoWPType", "[]")))]),
            BATCH_NAME=value.get("batchName", ""),
            DATE_MA_BEGIN=format_poster_date(value.get("dateMaBegin", "")),
            DATE_MA_END=format_poster_date(value.get("dateMaEnd", "")),
            DATE_STAT_BEGIN=format_poster_date(value.get("dateStatBegin", "")),
            DATE_STAT_END=format_poster_date(value.get("dateStatEnd", "")),
            # PATH=r"F:\Chan\docs\object_import_demo.csv"
            PATH=value.get("path", "")

        ),
        "wp_record_save": dict(
            PARAM_NAME=value.get("paramName", ""),
            PARAM_TYPE=format_poster_value(value.get("paramType", "")),
            COL_TYPE=format_poster_value(value.get("colType", "")),
            REQUIRED=format_poster_value(value.get("required", "")),
            COL_DEFAULT=value.get("colDefault", ""),
            GROUP_NAME=value.get("groupName", ""),
            ORDER_BY=str(value.get("orderBy", "")),
            MODIFY_DAY=value.get("modifyDay", ""),
            DEPEND_ON=value.get("dependOn", ""),
            DEPEND_RC_ID=value.get("dependRcId", ""),
            DEPEND_VALUE=value.get("dependValue", ""),
        )
    }.get(func_name, {})
    return {k: quote(str(v).strip()) for k, v in var.items()}


# 格式化中文为对应提交字段
def format_poster_value(value):
    result = {
        # 新增派单 -- 组件
        "外系统": "C",
        "电信": "S",
        # 营销政策 -- 营销类别
        "增值": "Z",
        "其他": "O",
        "移动": "M",
        "宽带": "K",
        # 营销政策 -- 是否重点
        "重点": "Y",
        "非重点": "N",
        # 添加，修改参数 -- 来源
        "清单导入": "30",
        "数据组.升光": "90",
        "数据组.提速": "120",
        "数据组.用户欠费": "150",
        "数据组": "750",
        "自定义.光宽渗透率": "60",
        "ODS.所属网格单元": "330",
        # 添加，修改批次 -- 提交按钮类型
        "导入号码清单": "I",
        "提交并导入号码清单": "SI",
        "提交": "S",
        "是": "Y",
        "否": "N",
        # 添加，修改批次 -- 自动派单方式
        "所属责任田负责人": "D",
        "所属门店负责人": "S",
        "所属片区经理": "A",
        "所属中心接单人": "J",
        "所属揽收人": "L",
        "自定义客户经理": "I",
        # 反馈定义 -- 参数类型
        "字符串": "S",
        "数字": "N",
        "定位": "D",
        "拍照": "P",
        # 反馈定义 -- 字段类型
        "文本输入": "E",
        "下拉框": "C",
        # 反馈定义 -- 依赖关系
        "下拉联动依赖": "C",
        "取值有效依赖": "V",
    }.get(value, value)
    return result


# 　格式化时间
def format_poster_date(date):
    if not any(date):
        return
    datetime_obj = datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
    datetime_str = datetime_obj.strftime("%Y-%m-%d")
    return datetime_str


# 构建"参数"提交字段
def build_wp_params(po_params):
    if not any(po_params):
        return " ", " "
    var_names = [""] * 30
    var_source = var_names.copy()
    for item in po_params:
        param_code = item.get("paramCode", "")
        param_name = item.get("paramName", "")
        param_source = format_poster_value(item.get("paramSource", ""))
        if not any(param_code) or \
                not any(param_name) or \
                not any(param_source):
            raise AttributeError('one of args is empty in id {id}:'
                                 'param_code : {param_code},'
                                 'param_name : {param_name},'
                                 'param_source : {param_source}'
                                 .format(id=item.get("id", ""),
                                         param_code=param_code,
                                         param_name=param_name,
                                         param_source=param_source))
        index = int(param_code[-2:])
        var_names[index] = param_name
        var_source[index] = param_source
    return ",".join(var_names), ",".join(var_source)


